import BpmnModeler from "@/module/main/other/BpmnTestView/BpmnModeler";
import {Component, ComponentProps, Mut, VueComponent} from "vue3-oop";
import {NForm, NFormItemGi, NGrid, NSelect} from "naive-ui";

interface IProps {
  bpmnModeler: BpmnModeler,
  elementId: string,
  elementName: string,
  elementType: string
}
@Component()
export default class Index extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    bpmnModeler: {default: {} as any},
    elementId: {default: ''},
    elementName: {default: ''},
    elementType: {default: ''}
  }

  @Mut() state = {
    messageId: '',
    messageList: [] as any[],
    messageNames: new Map<string,string>(),
  }

  private handleUpdateMessageId=(value:any)=>{
    this.state.messageId = value;
    this.updatePropsToElement();
  }

  private loadPropsFromElement=()=>{
    const element = this.props.bpmnModeler.getSelectedElement();
    this.state.messageId = element.businessObject.messageRef?.id;
    const rootElements = this.props.bpmnModeler.getDefinitions().rootElements as any[];
    this.state.messageList = [];
    this.state.messageNames.clear();
    rootElements
      .filter(el => el.$type === "bpmn:Message")
      .forEach(el=>{
        this.state.messageList.push({value:el.id,label:el.name})
        this.state.messageNames.set(el.id,el.name);
      })
  }

  private updatePropsToElement=()=>{
    let propsObj = {
      messageRef: null
    } as any;
    if(this.state.messageId && this.state.messageId.length>0){
      propsObj.messageRef = {
        id: this.state.messageId,
        name: this.state.messageNames.get(this.state.messageId)
      }
    }
    this.props.bpmnModeler.getModeling().updateProperties(this.props.bpmnModeler.getSelectedElement(), propsObj);
  }

  render(){
    this.loadPropsFromElement();
    return (
      <NForm labelPlacement="left" labelWidth={100}>
        <NGrid cols={2} xGap={20}>
          <NFormItemGi label="消息实例"><NSelect value={this.state.messageId} options={this.state.messageList} onUpdateValue={this.handleUpdateMessageId} /></NFormItemGi>
        </NGrid>
      </NForm>
    )
  }
}